<template>
  <a-modal
    :title="title"
    :width="800"
    :ok=false
    :visible="visible"
    :confirmLoading="confirmLoading"
    :okButtonProps="{ props: {disabled: disableSubmit} }"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">

    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
       
        <!-- <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="编号">
          <a-input placeholder="请输入编号" v-decorator="['serialNo', validatorRules.serialNo ]"/>
        </a-form-item> -->
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="项目名">
          <a-tree-select style="width:100%" :dropdownStyle="{maxHeight:'200px',overflow:'auto'}"
                         allow-clear :treeDefaultExpandAll="true"
               :treeData="categoryTree" v-decorator="[ 'parentId' ]" placeholder="请选择项目名称">
          </a-tree-select>
        </a-form-item>

         <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="名称">
          <a-input placeholder="请输入名称" v-decorator="['name', validatorRules.name ]"/>
        </a-form-item>
        <!-- <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="排序">
          <a-input-number v-decorator="[ 'sort' ]"/>
        </a-form-item> -->
        <!-- <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="备注">
          <a-textarea placeholder="请输入备注" :rows="2" v-decorator.trim="[ 'remark' ]" />
        </a-form-item> -->
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
  import { httpAction } from '@/api/manage'
  import { queryMaterialCategoryTreeList, checkMaterialCategory } from '@/api/api'
  import pick from 'lodash.pick'
  import ATextarea from 'ant-design-vue/es/input/TextArea'
  export default {
    name: "MaterialAddSubModal",
    components: { ATextarea },
    data () {
      return {
        categoryTree:[],
        orgTypeData:[],
        phoneWarning:'',
        departName:"",
        title:"操作",
        visible: false,
        disableSubmit:false,
        model: {},
        menuhidden:false,
        menuusing:true,
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },

        confirmLoading: false,
        form: this.$form.createForm(this),
        validatorRules:{
          name: {
            rules: [
              {required: true, message: '请输入名称!'},
              { validator: this.validateName}
            ]
          },
          serialNo: {rules: [{required: true, message: '请输入编号!'}]}
        },
        url: {
          add: "/materialCategory/add",
        }
      }
    },
    created () {
    },
    methods: {
      loadTreeData(){
        var that = this;
        let params = {};
        params.id='';
        queryMaterialCategoryTreeList(params).then((res)=>{          
          if(res){
            that.categoryTree = [];
            for (let i = 0; i < res.length; i++) {
              let temp = res[i];
              delete temp.children;
              that.categoryTree.push(temp);
            }   
          }
        })
      },
      add () {        
        this.edit();
      },
      edit (record) {       
        this.form.resetFields();
        this.visible = true;
        this.loadTreeData(); //获取分类用户树

        if(record == ""|| record == undefined || record == null){
          return
        }
        this.model = Object.assign({}, record);
       
       
        this.$nextTick(() => {    
          this.form.setFieldsValue({parentId:record.parentid, name:record.name}); 

        });
      },
      close () {      
        this.$emit('close');
        this.disableSubmit = false;
        this.visible = false;
      },
      handleOk () {     
        const that = this;
      
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let formData = Object.assign(this.model, values);
           
            //console.log(formData)

            if(this.model.id){
              let data = {
                checked: false,
                children:[],
                // id: formData.childid,
                id:formData.id,
                // key: formData.childid,
                key:formData.id,
                name: formData.name,
                parentId: formData.parentId,
                remark: null,
                serialNo: "1",
                sort: null,
                state: "open",
                title: "",
                // value: formData.childid
                value:formData.id
              }
            
              httpAction("/materialCategory/update",data,"put").then((res)=>{
                if(res.code == 200){
                  that.$message.success(res.data.message);
                  that.loadTreeData();
                  that.$emit('sueditok');
                }else{
                  that.$message.warning(res.data.message);
                }
              }).finally(() => {
                that.confirmLoading = false;
                that.close();
              })


            }else{
              httpAction(this.url.add,formData,"post").then((res)=>{            
                if(res.code == 200){
                  that.$message.success(res.data.message);
                  that.loadTreeData();               
                  that.$emit('subok');
                  //that.$refs.modalsubForm()
                }else{
                  that.$message.warning(res.data.message);
                }
              }).finally(() => {
                that.confirmLoading = false;
                that.close();
              })
            }
          }
        })
      },
      handleCancel () {
        this.close()
      },
      validateName(rule, value, callback){
        // let params = {
        //   name: value,
        //   id: this.model.id?this.model.id:0
        // };
        // checkMaterialCategory(params).then((res)=>{
        //   if(res && res.code===200) {
        //     if(!res.data.status){
        //       callback();
        //     } else {
        //       callback("名称已经存在");
        //     }
        //   } else {
        //     callback(res.data);
        //   }
        // });
      

        if(value == undefined || value.trim() == ""){
          callback("名称不能为空");
        }else{
          callback();  //就是一定要有callback的使用，也就是即使没有错误不需要提示也要写一句callback（）；否则的话 当你提交的时候 summit方法中的this.form.validateFields() 这个方法调用的时候回抛异常，但是浏览器捕获不到，控制台也不能打印出来错误，后果就是一直单击提交按钮页面没有任何反应，控制台没有任何报错，太坑了
                      //原文链接：https://blog.csdn.net/zhuangjiajia09/article/details/124966815
        }
      }
    }
  }
</script>

<style scoped>

</style>